/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * AtomXXX类可以保证可见性吗？请写一个程序来证明  可以
 *
 * @version 1.0
 * @since 17
 */
public class T32 {
    static AtomicBoolean flag = new AtomicBoolean(true);

    //volatile 可见性，不保证原子操作
    static volatile boolean flag2 = true;
    static boolean flag3 = true;

    public static void vol(String[] args) {
        //线程一
        new Thread(() -> {
            String tn = Thread.currentThread().getName();
            System.out.printf("线程启动：%s %n", tn);
            while (flag2) {

            }
            System.out.printf("线程：%s结束了%n", tn);
        }, "T1").start();
        //main线程
        try {
            TimeUnit.SECONDS.sleep(3);
            flag2 = false;
            System.out.println("Main设置了flag = false;");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //线程一
        new Thread(() -> {
            String tn = Thread.currentThread().getName();
            System.out.printf("线程启动：%s %n", tn);
            while (flag.get()) {

            }
            System.out.printf("线程：%s结束了%n", tn);
        }, "T1").start();
        //main线程
        try {
            TimeUnit.SECONDS.sleep(3);
            flag.set(false);
            System.out.println("Main设置了（flag.set(false);）");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
